package com.fzy.core.utils;

import ge.core.system.service.DictEntryListMapper;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import javax.servlet.ServletRequest;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.context.SecurityContext;
import org.acegisecurity.context.SecurityContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fzy.core.BaseService;
import com.fzy.core.acegi.UserDetailsImpl;

public class U {

	private static final Logger log = LoggerFactory.getLogger(U.class);
	
	private static BaseService baseService;
	
	private static DictEntryListMapper dictEntryListMapper;

	public static final String SYSDATE = "sysdate";
	public static final String DEFAULT_PROPERTIES = "application.properties";
		
	public void setBaseService(BaseService baseService) {
		U.baseService = baseService;
	}

	public void setDictEntryListMapper(
			DictEntryListMapper dictEntryListMapper) {
		U.dictEntryListMapper = dictEntryListMapper;
	}

	public static BaseService getBaseService() {
		return baseService;
	}
	
	public static String sequence2string(long value, int length){
		String result = value + "";
		for (int i = result.length(); i < length; i++) {
			result = "0" + result;
		}
		return result;
	}
	
	public static Long getUser() {
		UserDetailsImpl u = getCurrentUserdDetails();
		if(u != null) return u.getId();
		return new Long(0);
	}

	public static String getUserString() {
		UserDetailsImpl u = getCurrentUserdDetails();
		if(u != null) return u.getUsername();
		return "0";
	}

	public static String getUserEmployeeName() {
		UserDetailsImpl u = getCurrentUserdDetails();
		if(u != null) return u.getEmployeeName();
		return "";
	}

	public static UserDetailsImpl getCurrentUserdDetails() {
		SecurityContext s = SecurityContextHolder.getContext();
		if (s != null && s.getAuthentication() != null
				&& s.getAuthentication().getPrincipal() != null) {
			Object obj = s.getAuthentication().getPrincipal();
			if (obj instanceof UserDetailsImpl) {
				return (UserDetailsImpl) obj;
			}
		}
		return null;
	}
	
	public static String getCurrentUserGrpCode(){
		UserDetailsImpl u = getCurrentUserdDetails();
		if(u != null) return u.getGroupCode();
		return "";
	}
	
	public static boolean isZbZydUser(String userId){
		boolean flag = false;
		Long id = NumberUtils.createLongSafely(userId);
		if(id == null) return false;
		List l = getBaseService().queryForList("select b.userid from auth_rolemsg a, auth_userrolerel b where a.roleid = b.roleid and a.rolename = 'RU_ZB_ZYD' and b.userid = ?", new Long[]{id});
		if(l != null && l.size() > 0)
			flag = true;
		return flag;
	}
	
	public static boolean isZbUserForCurrentUser(){
		boolean flag = false;
		UserDetailsImpl u = getCurrentUserdDetails();
		flag=judgeRole(u,"ru_zb");
		return flag;
	}
	
	public static boolean isRsscUserForCurrentUser(){
		boolean flag = false;
		UserDetailsImpl u = getCurrentUserdDetails();
		flag=judgeRole(u,"ru_rssc");
		return flag;
	}
	
	public static boolean isDealerUserForCurrentUser(){
		boolean flag = false;
		UserDetailsImpl u = getCurrentUserdDetails();
		flag=judgeRole(u,"ru_dealer");
		return flag;
	}
	
	public static boolean isPassportUserForCurrentUser(){
		boolean flag = false;
		UserDetailsImpl u = getCurrentUserdDetails();
		flag=judgeRole(u,"ru_passport");
		return flag;
	}
	
	private static boolean judgeRole(UserDetailsImpl u,String roleName){
		boolean flag=false;		
		if(u!=null){
			GrantedAuthority[] g=u.getAuthorities();
			if(g!=null){
				for (int i = 0; i < g.length; i++) {
					GrantedAuthority tmp = g[i];
					if(tmp.getAuthority()!=null&&tmp.getAuthority().toLowerCase().equals(roleName)){
						flag=true;
						break;
					}						
				}
			}
		}
		return flag;
	}
	
	/**
	 * 必须是 EntityId 或 IIdStringEntity 的 list
	 * 
	 * @param list
	 * @return
	 */
	public static List getIdList(List list) {
		List result = new ArrayList();
		if (list == null || list.size() < 1)
			return result;
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Map o = (Map) iterator.next();			 
			result.add(o.get("id"));			 
		}
		return result;
	}


	public static Map getParameters(ServletRequest request) {
		Map params = new TreeMap();
		if (request == null)
			return params;
		Enumeration paramNames = request.getParameterNames();
		while (paramNames != null && paramNames.hasMoreElements()) {
			String paramName = (String) paramNames.nextElement();
			String[] values = request.getParameterValues(paramName);
			if (values == null || values.length == 0) {
				// Do nothing, no values found at all.
			} else if (values.length > 1) {
				params.put(paramName, values);
			} else {
				params.put(paramName, values[0]);
			}
		}
		return params;
	}
	
	public static String getAppPath(){
		String result = null;
		Properties ps = getProperties("application.properties");
		result = ps.getProperty("app.path");
		if(StringUtils.isBlank(result)){
			result = getAbsolutePath("../../");
		}
		if(!StringUtils.endsWith(result, "/")){
			result += "/";
		}
		return result;
	}

	public static String getClassPath() {
//		return U.class.getClassLoader().getResource(".").getPath();
		return U.class.getResource("/").getPath();
	}
	public static String getAbsolutePath(String relativePath) {
		Class loadClass = U.class;
		URL url = loadClass.getResource("/");
		relativePath = url.getPath() + relativePath;
		File dir = new File(relativePath);
		if (dir.exists() && dir.isDirectory()) {
		} else {
			dir.mkdirs();
		}
		return relativePath;
	}
	
	public static Properties getProperties() {
		return getProperties(DEFAULT_PROPERTIES);
	}

	public static Properties getProperties(String propertiesPath) {
		Properties result = new Properties();
		if (StringUtils.isBlank(propertiesPath))
			return result;
		String classPath = getClassPath();
		File f = new File(classPath + propertiesPath);
		if (f.canRead())
			try {
				result.load(new FileInputStream(f));
			} catch (Exception e) {
				log.error("propertiesPath:["+propertiesPath+"]");
				log.error(e.getMessage(), e);
			}
		return result;
	}

}
